/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.emove.modular.system.controller;

import cn.emove.config.properties.GunsProperties;
import cn.emove.core.common.annotion.BussinessLog;
import cn.emove.core.common.annotion.Permission;
import cn.emove.core.common.constant.Const;
import cn.emove.core.common.constant.dictmap.DeptDict;
import cn.emove.core.common.constant.dictmap.UserDict;
import cn.emove.core.common.exception.BizExceptionEnum;
import cn.emove.core.common.page.LayuiPageFactory;
import cn.emove.core.log.LogObjectHolder;
import cn.emove.core.util.HttpUtil;
import cn.emove.modular.system.entity.Meter;
import cn.emove.modular.system.entity.MeterReading;
import cn.emove.modular.system.model.MeterReadingDto;
import cn.emove.modular.system.model.OrderDto;
import cn.emove.modular.system.service.DictService;
import cn.emove.modular.system.service.MeterReadingService;
import cn.emove.modular.system.service.MeterService;
import cn.emove.modular.system.service.UserService;
import cn.emove.modular.system.warpper.MeterReadingWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 系统管理员控制器
 *
 * @author fengshuonan
 * @Date 2017年1月11日 下午1:08:17
 */
@Controller
@RequestMapping("/meterReading")
public class MeterReadingController extends BaseController {

    private static String PREFIX = "/modular/system/meter/";

    @Autowired
    private GunsProperties gunsProperties;

    @Autowired
    private MeterReadingService meterReadingService;

    @Autowired
    private MeterService meterService;

    @Autowired
    private UserService userService;

    @Autowired
    private DictService dictService;


    /**
     * 跳转到查看管理员列表的页面
     *
     * @author jiaojiaxiang
     * @Date 2019/04/18 10:50
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "meterReading.html";
    }
    @RequestMapping("/list")
    @Permission
    @ResponseBody
    public Object list(@RequestParam(required = false) String meterNo,
                       @RequestParam(required = false) String shopName,
                       @RequestParam(required = false) String shopAdr,
                       @RequestParam(required = false) String monthTime,
                       @RequestParam(required = false) String auditStatus,
                       @RequestParam(required = false) String meterType,
                       @RequestParam(required = false) String meterModel) {

        //拼接查询条件
        if (ToolUtil.isNotEmpty(monthTime)) {
            monthTime = monthTime.replace("-","");

        }
        String selectFlag = "1";
        Page<Map<String, Object>> meterReadings = meterReadingService.selectMeterReadings(null, meterNo,shopName, shopAdr, monthTime,auditStatus,meterType, selectFlag,meterModel);
        Page wrapped = new MeterReadingWrapper(meterReadings).wrap();
        return LayuiPageFactory.createPageInfo(wrapped);

    }


    /**
     * 跳转到抄表添加页面
     *
     * @author jiaojiaxiang
     *      * @Date 2019/04/18 10:50
     **/
    @RequestMapping(value = "/add")
    public String roleAdd() {
        return PREFIX + "meterReading_add.html";
    }

    /**
     * 查询商户下拉框
     * @return
     */
    @RequestMapping("/shopData")
    @ResponseBody
    public JSONObject selectShopData(){
        List<Map<String,Object>> userList = new ArrayList<Map<String,Object>>();
        userList = userService.selectShopData();
        JSONObject ServerJson = new JSONObject();
        for (Map<String,Object> c : userList) {
            ServerJson.put(String.valueOf(c.get("shopId")), c.get("shopName"));
        }
        return ServerJson;
    }

    @RequestMapping(value = "/addSave")
    @BussinessLog(value = "保存", key = "shopId", dict = UserDict.class)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public ResponseData addSave(OrderDto orderDto) {
        String ip = dictService.selectByCode("service_intranet_ip").get(0).getDescription();
        String url = ip+"/api/backstage/backstageOrderSave";
        String param = JSON.toJSONString(orderDto);
        String result = HttpUtil.post(url,param);
        System.out.println(result);
        if(result!=""){
            JSONObject json = JSONObject.parseObject(result);
            String code = String.valueOf(json.get("code"));
            if("200".equals(code)){
                return SUCCESS_TIP;
            }else{
                throw new ServiceException(BizExceptionEnum.SERVER_ERROR);
            }
        }else {
            throw new ServiceException(BizExceptionEnum.SESSION_TIMEOUT);
        }

    }


    // 导入
    /**
     * 实现文件上传
     * */
    @RequestMapping(value = "/importData", method = RequestMethod.POST)
    @ResponseBody

    public JSONObject importTemplate(@RequestParam("file") MultipartFile file) {
        JSONObject json = new JSONObject();
        FileInputStream excelFileIn = null;
        int successNum = 0;
        int failNum= 0;
        int nullNum = 0;
        StringBuffer msg = new StringBuffer();
        if (!file.isEmpty()) {
            try {
                String filename = file.getOriginalFilename();
                boolean isExcel2003 = true;
                if (filename.matches("^.+\\.(?i)(xlsx)$")) {
                    isExcel2003 = false;
                }
                InputStream is = file.getInputStream();
                HSSFWorkbook wb = null;
                if (isExcel2003) {
                    wb = new HSSFWorkbook(is);
                }
                Sheet sheet = wb.getSheetAt(0);
                Sheet_Data:for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                    row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                    row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                    row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                    row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                    row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
                    if(row.getCell(6)==null){
                        msg.append("第"+r+"行，能源表模式不能为空 <br/>");
                        failNum = failNum+1;
                        continue;
                    }
                    row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
                    row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);

                    if(row.getCell(8)==null){
                        msg.append("第"+r+"行，止码不能为空 <br/>");
                        failNum = failNum+1;
                        continue;
                    }
                    row.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
                    //MeterReadingDto meterReading = new MeterReadingDto();


                    String month = row.getCell(0).getStringCellValue();
                    String meterNo = row.getCell(5).getStringCellValue();
                    MeterReadingDto meterReading = null;
                    List<MeterReadingDto> meterReadingList = meterReadingService.selectDataListexist(month, meterNo);
                    Integer meterTypeTemp = 0;
                    String auditStatus = "";
                    if(meterReadingList.size()<=0){
                        meterReading = new MeterReadingDto();
                    }else {
                        for(MeterReadingDto meterReadingDto : meterReadingList){
                            meterTypeTemp = meterReadingDto.getMeterType();
                            auditStatus = meterReadingDto.getAuditStatus();
                            if((meterTypeTemp==1||meterTypeTemp==2)&&"1".equals(auditStatus)){
                                msg = msg.append("第"+r+"行，此数据本月已审核，如需修改请联系管理员！<br/>");
                                failNum = failNum+1;
                                continue Sheet_Data;
                            }
                            if((meterTypeTemp==1||meterTypeTemp==2)&&"3".equals(auditStatus)){
                                msg = msg.append("第"+r+"行，此数据本月已上传，如需修改请联系管理员！<br/>");
                                failNum = failNum+1;
                                continue Sheet_Data;
                            }

                            if((meterTypeTemp==3||meterTypeTemp==4)&&"1".equals(auditStatus)){
                                msg = msg.append("第"+r+"行，此服务费数据本月已审核，如需修改请联系管理员！<br/>");
                                failNum = failNum+1;
                                continue Sheet_Data;
                            }
                            if((meterTypeTemp==3||meterTypeTemp==4)&&"3".equals(auditStatus)){
                                msg = msg.append("第"+r+"行，此服务费数据本月已上传，如需修改请联系管理员！<br/>");
                                failNum = failNum+1;
                                continue Sheet_Data;
                            }
                        }
                        meterReading = meterReadingList.get(0);
                        if(meterReading.getMeterType()==3||meterReading.getMeterType()==4){
                            meterReadingService.removeById(meterReadingList.get(0).getId());
                            meterReading = new MeterReadingDto();
                        }

                    }

                    meterReading.setDataSourse("PC");
                    if(month==null||"".equals(month)||meterNo==null||"".equals(meterNo)||month.length()!=6){
                        msg = msg.append("第"+r+"行，导入模板中所属月份字段数据错误<br/>");
                        failNum = failNum+1;
                        continue;
                    }
                    meterReading.setMeterRedingMonth(month);
                    meterReading.setShopAdr(row.getCell(1).getStringCellValue());
                    meterReading.setShopName(row.getCell(2).getStringCellValue());
                    String meterType = row.getCell(4).getStringCellValue();
                    if("水表".equals(meterType)){
                        meterReading.setMeterType(1);
                    }else if("电表".equals(meterType)){
                        meterReading.setMeterType(2);
                    }else{
                        msg = msg.append("第"+r+"行，表类型字段数据错误<br/>");
                        failNum = failNum+1;
                        continue;
                    }
                    meterReading.setContractCode(row.getCell(3).getStringCellValue());
                    Map contract = meterService.selectContract(row.getCell(3).getStringCellValue());
                    meterReading.setContractStartDate(contract.get("startdate").toString());
                    meterReading.setContractEndDate(contract.get("enddate").toString());
                    meterReading.setMeterNo(meterNo);

                    String meterModel = row.getCell(6).getStringCellValue();
                    if("商铺".equals(meterModel)){
                        meterReading.setMeterModel("1");
                    }else if("广告位".equals(meterModel)){
                        meterReading.setMeterModel("2");
                    }else if("临时场地".equals(meterModel)){
                        meterReading.setMeterModel("3");
                    }else{
                        msg = msg.append("第"+r+"行，能源表模式字段数据错误<br/>");
                        failNum = failNum+1;
                        continue;
                    }
                    String startMun = row.getCell(7).getStringCellValue();
                    Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
                    Matcher isNum = pattern.matcher(startMun);
                    if( !isNum.matches() ){
                        msg = msg.append("第"+r+"行，起码填写格式不对，请填写数字<br/>");
                        failNum = failNum+1;
                        continue;
                    }
                    //获取起码
                    //查询上一次这家电表的止码
                    meterReading.setStartMum(startMun);
                    if(row.getCell(8)!=null&&!"".equals(row.getCell(8).toString())){
                        String endMun = row.getCell(8).toString();
                        Matcher isNum1 = pattern.matcher(endMun);
                        if( !isNum1.matches() ){
                            msg = msg.append("第"+r+"行，止码填写格式不对，请填写数字<br/>");
                            failNum = failNum+1;
                            continue;
                        }
                        meterReading.setEndMum(endMun);
                    }else{
                        msg = msg.append("第"+r+"行，未填止码<br/>");
                        nullNum = nullNum+1;
                        continue;
                    }
                    BigDecimal  currentMun = new BigDecimal(meterReading.getEndMum()) .subtract(new BigDecimal(meterReading.getStartMum())) ;
                    if(currentMun.compareTo(BigDecimal.ZERO)==-1){
                        msg = msg.append("第"+r+"行，起码大于或等于止码<br/>");
                        failNum = failNum+1;
                        continue;
                    }
                    if(currentMun.compareTo(BigDecimal.ZERO)==0){
                        meterReading.setCurrentMum("0");
                    }else {
                        meterReading.setCurrentMum(String.valueOf(currentMun));
                    }

                    //获取倍率，查询单价倍率表查询倍率
                    Meter meter = meterService.selectMeterByParam(meterNo, meterReading.getMeterType());
                    if(meter==null){
                        msg = msg.append("第"+r+"行，没有对应的能源表信息<br/>");
                        continue;
                    }

                    meterReading.setTimesRate(meter.getTimesRate());
                    meterReading.setUnitPrice(meter.getUnitPrice());
                    meterReading.setDiscount(meter.getDiscount());
                    //转换折扣
                    Double discount = Double.parseDouble(NumberFormat.getPercentInstance().parse(meter.getDiscount()).toString()) ;
                    //打折后的总价
                    double totalPrice = Double.valueOf(meterReading.getUnitPrice()) * Double.valueOf(meterReading.getCurrentMum())*Double.valueOf(meterReading.getTimesRate())*discount;
                    //浮动调整价格
                    double floatAdjust = Double.valueOf(meterReading.getUnitPrice()) * Double.valueOf(meterReading.getCurrentMum())*Double.valueOf(meterReading.getTimesRate())*(1-discount);
                    meterReading.setTotlePrice(String.format("%.4f", totalPrice));
                    meterReading.setFloatAdjust("-"+String.format("%.4f", floatAdjust));
                    meterReading.setAuditStatus("0");
                    meterReading.setStatus("1");
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    meterReading.setCreateTime(simpleDateFormat.format(new Date()));
                    //MeterReading data = meterReadingService.selectDataexist(month, meterNo);


                    Integer num = meterReadingService.updateOrInsert(meterReading);
                    //如果存在就修改
                    successNum = successNum+1;
                    if(!"".equals(meter.getLoseServiceCharge())&&meter.getLoseServiceCharge()!=null){

                        if(meterReading.getMeterType()==1){
                            meterReading.setMeterType(3);
                        }else if(meterReading.getMeterType()==2){
                            meterReading.setMeterType(4);
                        }

                        meterReading.setUnitPrice(meter.getLoseServiceCharge());
                        double totalLosePrice = Double.valueOf(meterReading.getUnitPrice()) * Double.valueOf(meterReading.getCurrentMum())*Double.valueOf(meterReading.getTimesRate())*discount;
                        double floatAdjustLosePrice = Double.valueOf(meterReading.getUnitPrice()) * Double.valueOf(meterReading.getCurrentMum())*Double.valueOf(meterReading.getTimesRate())*(1-discount);
                        meterReading.setTotlePrice(String.format("%.4f", totalLosePrice));
                        meterReading.setFloatAdjust("-"+String.format("%.4f", floatAdjustLosePrice));
                        meterReading.setId(String.valueOf(Integer.parseInt(meterReading.getId())+1));
                        Integer loseNum = meterReadingService.updateOrInsert(meterReading);
                        successNum = successNum+1;
                    }

                }
                /*int num = 0;
                if(list.size()>0){
                    num = meterReadingService.insertBatch(list);
                }else{
                    json.put("code",0);
                    json.put("msg","没有可导入的数据，检查数据是否已存在");
                    return json;
                }*/
                } catch (Exception e) {
                    json.put("code",0);
                    json.put("msg","导入Excel版本格式有问题");
                    return json;
                }
                json.put("code",1);
                json.put("successNum",successNum);
                json.put("failNum",failNum);
                json.put("nullNum",nullNum);
                json.put("msg",msg);
                return json;
        } else {
            json.put("code",0);
            json.put("msg","没有可读取的文件");
            return json;
        }
    }
    /**
     * 跳转至审核页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/audit")
    public String meterReadingAudit(@RequestParam String ids,Model model) {
        if (ToolUtil.isEmpty(ids)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        ids = ids.substring(0,ids.lastIndexOf(","));
        model.addAttribute("ids", ids);
        LogObjectHolder.me().set(ids);
        return PREFIX + "meterReading_audit.html";
    }
    /**
     * 跳转至审核页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/cancelAudit")
    public String meterReadingCancelAudit(@RequestParam String ids,Model model) {
        if (ToolUtil.isEmpty(ids)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        ids = ids.substring(0,ids.lastIndexOf(","));
        model.addAttribute("ids", ids);
        LogObjectHolder.me().set(ids);
        return PREFIX + "meterReading_cancelAudit.html";
    }
    /**
     * 审核保存
     */
    @RequestMapping(value = "/auditSave")
    @ResponseBody
    public ResponseData audit(@RequestParam Integer flag,String ids,String remark) {
        String[] array = ids.split(",");
        String status = "";
        if(flag==0){
            status = "2";
        }else if(flag==1){
            status = "1";
        }
        ArrayList<String> strArray = new ArrayList<String> ();
        for(int i=0;i<array.length;i++){
            MeterReading meterReading = meterReadingService.selectById(Integer.valueOf(array[i]));
            if("3".equals(meterReading.getAuditStatus())){
                System.out.println("此数据已经上传");
            }else{
                strArray.add(array[i]);
            }
        }
        if(strArray.size()<=0){
            throw new ServiceException(BizExceptionEnum.DATA_AUDIT_ERROR);
        }
        Integer num = meterReadingService.updateBatch(strArray, status, remark);
        if(num>0){
            return SUCCESS_TIP;
        }else{
            throw new ServiceException(BizExceptionEnum.OPERATION_ERROR);
        }

    }
    /**
     * 删除抄表信息
     *
     * @author fengshuonan
     * @Date 2018/12/23 4:57 PM
     */
    @BussinessLog(value = "删除抄表信息", key = "meterReadingId", dict = DeptDict.class)
    @RequestMapping(value = "/delete")
    @Permission
    @ResponseBody
    public ResponseData delete(@RequestParam Integer meterReadingId) {
        meterReadingService.removeById(meterReadingId);
        return SUCCESS_TIP;
    }
}
